import {
  Alert,
  Linking,
  Permission,
  PermissionsAndroid,
  Platform,
} from "react-native"

export const requestPermission = async (permission: Permission) => {
  if (Platform.OS === "android") {
    try {
      const granted = await PermissionsAndroid.request(permission)
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("权限已授予")
        return true
      } else if (granted === PermissionsAndroid.RESULTS.DENIED) {
        Alert.alert("权限被拒绝", "功能受限，请考虑授予权限。")
        return Promise.reject(new Error("权限被拒绝,功能受限，请考虑授予权限"))
      } else {
        // 'never_ask_again'
        Alert.alert(
          "权限已被永久拒绝",
          "您已永久拒绝此权限。如需使用该功能，请到系统设置中手动开启。",
          [
            {text: "取消", style: "cancel"},
            {text: "去设置", onPress: () => Linking.openSettings()},
          ],
        )
        return Promise.reject(
          new Error(
            "您已永久拒绝此权限。如需使用该功能，请到系统设置中手动开启。",
          ),
        )
      }
    } catch (err) {
      console.warn(err)
      return Promise.reject(
        new Error(
          "您已永久拒绝此权限。如需使用该功能，请到系统设置中手动开启。",
        ),
      )
    }
  } else {
    // iOS已在Info.plist中配置权限
    return true
  }
}
// import {Alert, Permission, PermissionsAndroid, Platform} from "react-native"

// export const requestPermission = async (permission: Permission) => {
//   if (Platform.OS === "android") {
//     try {
//       const granted = await PermissionsAndroid.request(permission)
//       if (granted === PermissionsAndroid.RESULTS.GRANTED) {
//         return true
//       } else {
//         Alert.alert("权限被拒绝", "无法使用该功能")
//         return false
//       }
//     } catch (err) {
//       console.warn(err)
//       return false
//     }
//   } else {
//     // iOS已在Info.plist中配置权限
//     return true
//   }
// }
